<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户分页展示</title>
    <!--vue-->
    <script src="/js/vue.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/css/index.css">
    <!-- 引入组件库 -->
    <script src="/js/index.js"></script>
    <!--axios-->
    <script src="/js/axios.min.js"></script>

    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
        }
        .avatar {
            width: 100px;
            height: 100px;
            display: block;
        }
    </style>
</head>
<body>
    <div id="app">
        <el-row>
            <el-col :span="3">&nbsp;</el-col>
            <el-col :span="3"><el-input v-model="loginName"   size="mini" placeholder="请输名称"></el-input></el-col>
            <el-col :span="3"><el-input v-model="userName"   size="mini" placeholder="请输用户名"></el-input></el-col>
            <el-col :span="3"><el-input v-model="email"   size="mini" placeholder="邮箱"></el-input></el-col>
            <el-col :span="3"><el-input v-model="phoneNumber"   size="mini" placeholder="电话"></el-input></el-col>
            <el-col :span="3"><el-button type="primary" size="mini" @click="search()" icon="el-icon-search">搜索</el-button></el-col>
            <el-col :span="3"><el-button type="primary" size="mini" @click="toAdd()" icon="el-icon-circle-plus">添加</el-button></el-col>
            <el-col :span="3"><el-button type="primary" size="mini" @click="flush()" icon="el-icon-search">刷新</el-button></el-col>
        </el-row>
        <el-row>
                <el-table
                        :data="tableData"
                        style="width: 100%">
                    <el-table-column
                            prop="user_name"
                            label="用户名">
                    </el-table-column>
                    <el-table-column
                            prop="login_name"
                            label="名字">
                    </el-table-column>
                    <el-table-column
                            prop="role_name"
                            label="角色">
                    </el-table-column>
                    <el-table-column
                            prop="email"
                            label="邮箱">
                    </el-table-column>
                    <el-table-column
                            prop="phonenumber"
                            label="电话">
                    </el-table-column>
                    <el-table-column
                                prop="sex"
                                :formatter="getSexName"
                                label="性别">
                    </el-table-column>
                    <el-table-column
                            label="头像">
                        　<template slot-scope="scope">
                            <el-image
                                    style="width: 50px; height: 50px"
                                    :src="scope.row.avatar"
                                     ></el-image>
                         </template>
                        <!--<img :src="avatar" class="userAvatar"
                             style="display: block;width: 50px;height: 50px;
                         border-radius: 50%;-webkit-border-radius: 50%;
                         -moz-border-radius: 50%;
                         border: 4px solid #44576b;box-sizing: border-box;margin: 10px auto 10px;">-->
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            :formatter="getStatusName"
                            label="状态">
                    </el-table-column>
                    <el-table-column
                            prop="login_ip"
                            label="登录IP">
                    </el-table-column>
                    <el-table-column
                            prop="login_date"
                            label="最后一次登录时间">
                    </el-table-column>
                    <el-table-column label="操作"  width="250">
                        <template slot-scope="scope">
                            <el-button
                                    type="primary"
                                    size="mini"
                                    @click="toShowRoles(scope.$index, scope.row)">赋予角色</el-button>
                            <el-button
                                    size="mini"
                                    @click="toEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,100, 200, 300, 400]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <el-row>
            <!--添加弹出框-->
            <el-dialog title="添加" :visible.sync="addFormVisible">
                <el-form :model="addform">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="addform.user_name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="addform.login_name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色" :label-width="formLabelWidth">
                        <el-select v-model="addform.role_id" placeholder="请选择">
                            <el-option
                                    v-for="item in roles"
                                    :key="item.role_id"
                                    :label="item.role_name"
                                    :value="item.role_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth">
                        <el-input v-model="addform.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth">
                        <el-input v-model="addform.phonenumber" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-radio v-model="addform.sex" label="0">男</el-radio>
                        <el-radio v-model="addform.sex" label="1">女</el-radio>
                        <el-radio v-model="addform.sex" label="2">未知</el-radio>
                    </el-form-item>
                    <el-form-item label="头像上传" :label-width="formLabelWidth">
                        <!--图片上传-->
                        <el-upload
                                class="avatar-uploader"
                                action="/commonOSS/upload"
                                name="file"
                                :auto-upload='true'
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="addform.password" autocomplete="off" show-password></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
        <el-row>
            <!--更新弹出框-->
            <el-dialog title="更新" :visible.sync="updateFormVisible">
                <el-form :model="form">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="form.user_name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="form.login_name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth">
                        <el-input v-model="form.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth">
                        <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-radio v-model="form.sex" label="0">男</el-radio>
                        <el-radio v-model="form.sex" label="1">女</el-radio>
                        <el-radio v-model="form.sex" label="2">未知</el-radio>
                    </el-form-item>
                    <el-form-item label="头像" :label-width="formLabelWidth">
                        <el-image v-if="(form.avatar==''||form.avatar==null)?false:true"
                                style="width: 100px; height: 100px"
                                :src="form.avatar"
                        ></el-image>
                        <el-upload
                                class="avatar-uploader"
                                action="/commonOSS/upload"
                                name="file"
                                :auto-upload='true'
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="form.password" autocomplete="off" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-radio v-model="form.status" label="0">正常</el-radio>
                        <el-radio v-model="form.status" label="1">禁用</el-radio>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="updateFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="update()">确 定</el-button>
                </div>
            </el-dialog>
            <!--角色授权弹出框-->
            <el-dialog title="角色列表" :visible.sync="rolesVisible">
                <template>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                        <el-checkbox v-for="role in roles" :label="role.role_id" :key="role.role_id">{{role.role_name}}</el-checkbox>
                    </el-checkbox-group>
                </template>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addUserAndRole()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
    </div>
    <script>
         var vue = new Vue({
             el:"#app",
             data:{//数据
                 tableData:[],
                 currentPage:1,
                 pageSize:5,
                 total:20,
                 roleName:null,
                 addFormVisible:false,//添加对话框是否显示
                 updateFormVisible:false,//更新对话框是否显示
                 addform:{},
                 form:{},//更新form
                 formLabelWidth:"120px",
                 roleId:0,//角色id
                 loginName:'',
                 userName:'',
                 email:'',
                 phoneNumber:'',
                 rolesVisible:false,//角色列表弹出框
                 //用户关联角色相关的
                 checkAll: false,
                 checkedRoles:[],
                 roles:[],
                 isIndeterminate: true,
                 roleIds:'',
                 userId:0,
                 imageUrl:'',
             },
             created:function () {
                 _this =this;
                 //初始化数据，加载所有的角色
                 axios.get('/role/page',{
                     params: {
                             pageNo:1,
                             pageSize:1000
                     }
                 }).then(function (response) {
                         _this.roles=response.data.page;
                     });
                this.loadData();
             },
             methods:{//方法
                 //加载数据的方法
                 loadData:function () {
                     _this =this;
                     //初始化数据
                     axios.get('/user/page', {
                         params: {
                             pageNo:this.currentPage,
                             pageSize:this.pageSize,
                             loginName:this.loginName,
                             userName:this.userName,
                             email:this.email,
                             phoneNumber:this.phoneNumber,
                         }
                     })
                         .then(function (response) {
                             // handle success  处理成功，回调的方法
                             //console.log(response);
                             //赋值分页列表
                             _this.tableData = response.data.page;
                             //删除最后一页为空时，调到上一页
                             //alert(_this.tableData.length);
                             if(_this.tableData.length==0&&_this.currentPage!=1){
                                 _this.currentPage=_this.currentPage-1;
                                 _this.loadData();
                             }
                             //赋值总条数
                             _this.total = response.data.total;
                         })
                         .catch(function (error) {
                             // handle error 处理异常
                             //console.log(error);
                         })
                         .then(function () {
                             // always executed  总是执行  相当于finally
                         });
                 },
                 //每页数量发生变化时
                 handleSizeChange:function (v) {
                     this.pageSize=v;
                    this.loadData();
                 },
                 //当前页数放生变化是
                 handleCurrentChange:function (v) {
                    this.currentPage=v;
                    this.loadData();
                 },
                 // 搜索方法
                 search:function () {
                     this.currentPage=1;
                     this.loadData();
                 },
                 //跳转更新
                 toEdit:function (index,row) {
                     //清空原来的
                     this.form.avatar='';
                     this.form={};
                     this.roles=[];
                     this.form=row;
                     axios.get('/role/allRoles').then(function (response) {
                         vue.roles=response.data.list;
                     });
                     this.updateFormVisible=true;
                 },
                 toAdd:function(){
                     this.addform={};
                     this.addFormVisible=true;
                 },
                 //弹出角色选择对话框
                 toShowRoles:function (index,row){
                     this.userId=row.user_id;
                     //根据当前用户ID查询对应的所有角色id集合 赋值给默认选中checkedRoles
                     _this =this;
                     //初始化数据，加载所有的角色
                     axios.get('/user/listRoleIdsByUserId?userId='+row.user_id,).then(function (response) {
                         _this.checkedRoles=response.data;
                     });
                      this.rolesVisible=true;
                 },
                 //添加用户和角色关联方法
                 addUserAndRole(){
                     _this =this;
                     console.log("roleIds:"+this.roleIds);
                     if(this.roleIds.length<1){
                         _this.$message.error("至少选中一个角色。。。");
                         return;
                     }
                     //调用后台方法，添加数据库
                     axios.post('/user/addUserAndRole?userId='+this.userId+"&roleIds="+this.roleIds).then(function (response) {
                         console.log(response);
                         if(response.status == 200){
                             if(response.data>0) {
                                 //提示成功
                                 _this.$message({
                                     type: 'success',
                                     message: '添加成功!'
                                 });
                                 //关闭弹框
                                 _this.rolesVisible=false;
                                 //重新加载数据
                                 _this.loadData();
                             }
                         }
                     }).catch(function (error) {
                         console.log(error);
                         _this.$message.error("你错了。。。");
                     });
                 },
                 //删除
                 handleDelete:function (index,row) {
                     this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                         confirmButtonText: '确定',
                         cancelButtonText: '取消',
                         type: 'warning'
                     }).then(() => {
                         axios.post('/user/delete?userId='+row.user_id).then(function (response) {
                             console.log(response);
                             if(response.status == 200){
                                 if(response.data>0) {
                                     //提示成功
                                     _this.$message({
                                         type: 'success',
                                         message: '删除成功!'
                                     });
                                     //重新加载数据
                                     _this.loadData();
                                 }
                             }
                         }).catch(function (error) {
                             console.log(error);
                             _this.$message.error("你错了。。。");
                         });

                     }).catch(() => {
                         this.$message({
                             type: 'info',
                             message: '已取消删除'
                         });
                     });
                 },
                 //添加
                 add:function(){
                         _this = this;
                         axios.post('/user/add',this.addform).then(function (response) {
                             console.log(response);
                             if(response.status == 200){
                                 //提示成功
                                 _this.$message({
                                     message: '恭喜你，添加成功',
                                     type: 'success'
                                 });
                                 //_this.$message.success("恭喜你，添加成功");
                                 //关闭弹出框
                                 _this.addFormVisible=false;
                                 //重新加载数据
                                 _this.loadData();
                                 //清空form
                                 _this.addform={};
                             }
                         }).catch(function (error) {
                             console.log(error);
                             _this.$message.error("你错了。。。");
                         });
                 },
                 //更新
                 update:function(){
                     _this = this;
                     //JSON.stringify JSON 转 String
                     // alert(JSON.stringify(this.form));
                     axios.post('/user/update',this.form).then(function (response) {
                         console.log(response);
                         if(response.status == 200){
                             //提示成功
                             _this.$message({
                                 message: '恭喜你，操作成功',
                                 type: 'success'
                             });
                             //_this.$message.success("恭喜你，添加成功");
                             //关闭弹出框
                             _this.updateFormVisible=false;
                             //重新加载数据
                             _this.loadData();
                         }
                     }).catch(function (error) {
                         console.log(error);
                         _this.$message.error("你错了。。。");
                     });
                 },
                 //用户类型获取名称
                 getTypeName(row, column, cellValue) {
                     // return cellValue==0?'后台管理员':cellValue==1?"代理商":"商户";
                     var tmpType = "";
                     if (cellValue == 0) {
                         tmpType = "管理员";
                     } else if (cellValue == 1) {
                         tmpType = "代理商";
                     } else {
                         tmpType = "商户";
                     }
                     return tmpType;
                 },
                 //用户性别
                 getSexName(row, column, cellValue) {
                      return cellValue==0?'男':cellValue==1?"女":"未知";
                    /* var tmpType = "";
                     if (cellValue == 0) {
                         tmpType = "后台管理员";
                     } else if (cellValue == 1) {
                         tmpType = "代理商";
                     } else {
                         tmpType = "商户";
                     }
                     return tmpType;*/
                 },
                 //账户状态名字
                 getStatusName(row, column, cellValue) {
                     return cellValue == 0 ? '正常' :"禁用";
                 },
                 //处理全选改变
                  handleCheckAllChange(val) {
                     //console.log("。。。。"+val);
                     if(val) {//判断是否为true
                         for (var i = 0; i < this.roles.length; i++) {
                             this.checkedRoles.push(this.roles[i].role_id);
                         }
                     }else{
                         this.checkedRoles=[];
                     }
                     //this.checkedRoles = val ? this.roles : [];
                     this.isIndeterminate = false;
                 },
                 handleCheckedRolesChange(value) {

                     console.log("选中的："+value);
                     this.roleIds=value;
                     let checkedCount = value.length;

//                     console.log("双等："+('1'==1));//true
//                     console.log("三个等："+('1'===1));//false
//                     console.log("三个等："+('1'==='1'));//true
//                     console.log("三个等："+(1===1));//true
                     this.checkAll = checkedCount === this.roles.length; //=== 数据类和数据都要匹配
                                                                           //== 数据匹配
                     this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
                 },
                 flush(){
                     //刷新当前页
                     location.reload();
                 },
                 //图片上传成功后
                 handleAvatarSuccess:function(res, file) {
                     //图片回显
                     this.imageUrl = URL.createObjectURL(file.raw);
                  //   alert(file.response);
                    // alert(JSON.stringify(file.response));
                     this.form.avatar=file.response.ossFileUrlBoot;
                     // this.form.fileName=file.response.oldFileName;
                     // this.form.filePath=file.response.newFilePath;
                 },
                 //上传前图片类型和大小判断
                 beforeAvatarUpload:function(file) {
                     // const isJPG = file.type === 'image/jpeg';
                     const isLt2M = file.size / 1024 / 1024 < 2;

                     /* if (!isJPG) {
                          this.$message.error('上传头像图片只能是 JPG 格式!');
                      }*/
                     if (!isLt2M) {
                         this.$message.error('上传头像图片大小不能超过 2MB!');
                     }
                     return  isLt2M;
                 }
             }
         });
    </script>
</body>

</html>